package com.hfh.main.report.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hfh.main.common.annotate.JwtToken;
import com.hfh.main.common.method.DateRangeGenerator;
import com.hfh.main.common.method.commonMethod;
import com.hfh.main.common.resp.Result;
import com.hfh.main.course.entity.CourseListEntity;
import com.hfh.main.course.service.CourseListService;
import com.hfh.main.group.entity.GroupDetailEntity;
import com.hfh.main.group.entity.GroupEntity;
import com.hfh.main.group.service.GroupDetailService;
import com.hfh.main.group.service.GroupService;
import com.hfh.main.report.entity.DailyReportEntity;
import com.hfh.main.report.entity.WeekEntity;
import com.hfh.main.report.mapper.DailyReportMapper;
import com.hfh.main.report.service.DailyReportService;
import com.hfh.main.report.service.WeekService;
import com.hfh.main.user.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;

/**
 * <p>
 * 日报 前端控制器
 * </p>
 */
@Tag(name="日报管理")
@RestController
@RequestMapping("/dailyReportEntity")
public class DailyReportController {

    @Autowired
    private DailyReportMapper dailyReportMapper;
    @Autowired
    private DailyReportService dailyReportService;
    @Autowired
    private CourseListService courseListService;
    @Autowired
    private UserService userService;

    @Autowired
    GroupDetailService groupDetailService;

    @Autowired
    GroupService groupService;

    @Autowired
    WeekService weekService;

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

    @JwtToken
    @Operation(summary = "日报-列表-分页")
    @PostMapping("/listPage")
    public Result<?> listPage(@RequestParam Integer page, @RequestParam Integer pageSize, @RequestParam(required = false) String acc,
                              @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date startTime, @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date endTime) {
        //分页参数
        Page<DailyReportEntity> rowPage = new Page(page, pageSize);
        //queryWrapper组装查询where条件
        LambdaQueryWrapper<DailyReportEntity> queryWrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotEmpty(acc)) {
            queryWrapper.eq(DailyReportEntity::getAcc, acc);
        }
        if (startTime != null) {
            queryWrapper.ge(DailyReportEntity::getDate, startTime);
        }
        if (endTime != null) {
            queryWrapper.le(DailyReportEntity::getDate, endTime);
        }
        rowPage = dailyReportMapper.selectPage(rowPage, queryWrapper);
        List<DailyReportEntity> records = rowPage.getRecords();
        rowPage.setRecords(records);
        return Result.success("数据请求成功", rowPage);
    }

    /**
     * 查询-通过用户编号获取按周分组的日报
     * 此项目始于7月 刚好1号就是周一 暂时没问题
     * 后续优化 ： 分组是按自然周分还是按7天分
     */
    @JwtToken
    @Operation(summary = "查询-通过用户acc获取日报")
    @PostMapping("/getProjectByAcc/{acc}")
    public Result<?> getProjectByAcc(@PathVariable @Validated String acc) {
        //设置返回的数据
        HashMap rtn = new HashMap();
        //准备个人信息
        Map userInfo = userService.queryShowInfoByAcc(acc);
        if(userInfo != null) rtn.put("user", userInfo);
        //通过acc查所在组
        GroupDetailEntity gd = groupDetailService.getOne(new QueryWrapper<GroupDetailEntity>().eq("user_acc", acc));
        if(gd != null){
            String groupId = String.valueOf(gd.getGroupId());
            //通过组id查项目
            GroupEntity g = groupService.getOne(new QueryWrapper<GroupEntity>().eq("group_id", groupId));
            String listId = String.valueOf(g.getListId());
            //通过项目id查项目
            CourseListEntity courseListEntity = courseListService.getOne(new QueryWrapper<CourseListEntity>().eq("list_id", listId));
            //得到项目名
            rtn.put("projectName", courseListEntity.getName());
            //得到小组4次答辩分数
            rtn.put("db_first", g.getDbFirst());
            rtn.put("db_mid", g.getDbMid());
            rtn.put("db_second", g.getDbSecond());
            rtn.put("db_terminal", g.getDbTerminal());
            //得到个人最终得分
            rtn.put("db_final", userInfo.get("dbFinal"));

            rtn.put("startDate",dateFormat.format(courseListEntity.getStartDate()));
        }

        //通过acc查这个区间周 7天日报
        List<DailyReportEntity> days_list = dailyReportService
                .list(new QueryWrapper<DailyReportEntity>().eq("user_acc", acc)
                        .ge("date", rtn.get("startDate").toString()) //大于等于这天
                        .orderByAsc("date")
                        .last("limit 28")      ); //先查4周的数据 ，一个月跨4个周  后续优化

        //通过acc查当月所有周 ，按周序号排序
        List<WeekEntity> weeks = weekService.list(new QueryWrapper<WeekEntity>().eq("user_acc", acc).orderByAsc("week_number"));
        for(int i = 0; i < weeks.size(); i++){
            List<DailyReportEntity> days_list_add = new ArrayList<>();
            HashMap w;
            //设置计数
            Integer wrote = 0;
            try {
                w = (HashMap) commonMethod.objectToMap(weeks.get(i));
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }

            //补全自项目开始以来至今天的所有天，方便前台循环展示
            if(!"".equals(rtn.get("startDate"))){
                if(days_list.size() != 31){ //已保存的日志数不足31天 //后续优化 天数怎么确定
                    List<LocalDate> days = DateRangeGenerator.getPartition7Days(rtn.get("startDate").toString(), i); //获取当前周7天的日期
                    for(LocalDate date : days){
                        Boolean hasAdd = false;
                        //查找days_list中是否存在 date
                        for(DailyReportEntity d : days_list){
                            if(d.getDate().equals(date.toString())){
                                days_list_add.add(d);
                                if(d.getReport() != null && d.getSelfEval() != null && d.getSelfEval() != 0 ) { //日报和自评都不为空则认为已填写
                                    wrote++;
                                }
                                hasAdd = true;
                                break;
                            }
                        }
                        if(!hasAdd){
                            days_list_add.add(new DailyReportEntity().setDate(date.toString()));
                        }

                    }
                }
            }
            w.put("dailyReport", days_list_add);
            w.put("wrote", wrote==7);
            rtn.put("week"+weeks.get(i).getWeekNumber(), w);
        }
        return Result.success(rtn);
    }

    @JwtToken
    @Operation(summary = "日报-查询-编号")
    @PostMapping("/selectDailyReportByID/{param}")
    public Result<?> selectDailyReportByID(@PathVariable @Validated String param) {
        QueryWrapper<DailyReportEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(("id"), param);
        if (dailyReportService.count(wrapper) == 0) return Result.failure(500, "编号不存在", sdf.format(new Date()));
        return Result.success(dailyReportService.getOne(wrapper));
    }

    @JwtToken
    @Operation(summary = "日报-保存")
    @PostMapping("/insert")
    public Result<?> insert(@RequestBody @Validated DailyReportEntity entity) {
        QueryWrapper<DailyReportEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(("id"), entity.getId());
        if (dailyReportService.count(wrapper) != 0) return Result.failure(500, "编号已存在", sdf.format(new Date()));
        dailyReportService.save(entity);
        return Result.success("保存成功", sdf.format(new Date()));
    }

    @JwtToken
    @Operation(summary = "日报-修改")
    @PostMapping("/update")
    public Result<?> update(@RequestBody @Validated DailyReportEntity entity) {
        QueryWrapper<DailyReportEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(("id"), entity.getId());
        if (dailyReportService.count(wrapper) == 0) return Result.failure(500, "编号不存在", sdf.format(new Date()));
        dailyReportService.updateById(entity);
        return Result.success("修改成功", sdf.format(new Date()));
    }

    @JwtToken
    @Operation(summary = "日报-删除")
    @PostMapping("/delete/{param}")
    public Result<?> delete(@PathVariable @Validated String param) {
        QueryWrapper<DailyReportEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(("id"), param);
        if (dailyReportService.count(wrapper) == 0) return Result.failure(500, "编号不存在", sdf.format(new Date()));
        dailyReportService.remove(wrapper);
        return Result.success("保存成功", sdf.format(new Date()));
    }

}
